package com.diabetes.service.impl;

import com.diabetes.constant.MessageConstant;
import com.diabetes.dto.UserLoginDTO;
import com.diabetes.dto.UserRegisterDTO;
import com.diabetes.dto.UserUpdateDTO;
import com.diabetes.entity.SugarRecord;
import com.diabetes.entity.User;
import com.diabetes.exception.AccountNotFoundException;
import com.diabetes.exception.PasswordErrorException;
import com.diabetes.mapper.UserMapper;
import com.diabetes.service.UserService;
import com.diabetes.vo.getBloodVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //用户登录
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return user;
    }

    //用户注册
    public void register(UserRegisterDTO userRegisterDTO) {
        String username = userRegisterDTO.getUsername();
        String password = userRegisterDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理异常情况（用户名已存在）
        if (user != null) {
            //账号已经存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_HAVE_FOUND);
        }
        //进行md5加密，然后再进行插入
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        userMapper.insertAccount(username, password);
    }

    //个人信息更改
    public void update(UserUpdateDTO userUpdateDTO) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO, user);
        userMapper.update(user);
    }

    @Override
    public void search(SugarRecord sugarRecord) {
        SugarRecord su = new SugarRecord();
        BeanUtils.copyProperties(sugarRecord,su);
        su.setRecordDate(LocalDateTime.now());
        userMapper.search(su);
    }

    @Override
    public SugarRecord get(Integer ids) {
        return userMapper.getblood(ids);
    }
}
